package javango.http;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public abstract class BaseHttpResponse implements HttpResponse {

	private final static Log log = LogFactory.getLog(BaseHttpResponse.class);
	
//	public abstract void render(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws HttpException;

	protected Map<String, Object> context;

	protected int statusCode = 200;	
	protected Set<Cookie> cookies = new HashSet<Cookie>();
	protected String mimeType = "text/html";
	protected Map<String, String> headers = new HashMap<String, String>();
	
	/**
	 * Update the cookies, mime type, status code, etc headers
	 * 
	 * @param resp
	 */
	protected void updateResponse(HttpServletResponse resp) {
		
		if (log.isDebugEnabled()) log.debug("Updating response - Status: " + getStatusCode() + " ContentType: " + getMimeType());
		resp.setStatus(getStatusCode());
		resp.setContentType(getMimeType());

		for (Entry<String, String> e : headers.entrySet()) {
			resp.setHeader(e.getKey(), e.getValue());
		}

		for(Cookie c : getCookies()){
			// TODO cookie domain??
			resp.addCookie(c);
		}
		
	}
	
	public BaseHttpResponse addHeader(String key, String value, Object... args) {
		headers.put(key, String.format(value, args));
		return this;
	}
	
	public BaseHttpResponse setCookie(Cookie cookie){
		cookies.add(cookie);
		return this;
	}
	
	/**
	 * Sends a cookie with a maxAge of 0 to the client. This effectively clears
	 * the cookie on their end.
	 * 
	 * @param name the name of the cookie to clear
	 */
	public BaseHttpResponse clearCookie(String name){
		Cookie cookie = new Cookie(name, "");
		cookie.setMaxAge(0);
		cookies.add(cookie);
		return this;
	}


	public String getMimeType() {
		return mimeType;
	}

	public BaseHttpResponse setMimeType(String mimeType) {
		this.mimeType = mimeType;
		return this;
	}
	
	public int getStatusCode() {
		return statusCode;
	}

	public BaseHttpResponse setStatusCode(int statusCode) {
		this.statusCode = statusCode;
		return this;
	}

	public Set<Cookie> getCookies() {
		return cookies;
	}

	public BaseHttpResponse setCookies(Set<Cookie> cookies) {
		this.cookies = cookies;
		return this;
	}

	public Map<String, Object> getContext() {
		return context;
	}

	public BaseHttpResponse setContext(Map<String, Object> context) {
		this.context = context;
		return this;
	}
}
